import *as THREE from "three"

// 使用着色器代码 修改城市默认细节
export function modifyCityDefaultMaterial(mesh) {
  // 给现有材质追加着色器代码
  mesh.material.onBeforeCompile = (shader) =>{
    // 替换片元着色器内代码字符串
    // 对混色 dithering_fragment 部分准备改写
    // 打印shader.fragmentShader 发现是C 语法 引入了插件和实现过程代码 这里对C语法做出替换 让颜色改变
    shader.fragmentShader = shader.fragmentShader.replace(
      "#include <dithering_fragment>",
      `
        #include <dithering_fragment>
        //#end#
      `
    )
    addGradColor(shader, mesh)
  }
}
export function addGradColor(shader, mesh) {

  mesh.geometry.computeBoundingBox()

  let { min, max } =mesh.geometry.boundingBox
  let uHeight = max.z -min.z
  let uMaxX = max.x
  let uMinX = min.x

  shader.uniforms.uTopColor = {
    value: new THREE.Color("#ebe6e6")
  };
  shader.uniforms.uHeight = {
    value: uHeight
  };
  shader.uniforms.uMaxX = {
    value: uMaxX
  }
  shader.uniforms.uMinX = {
    value: uMinX
  }

  shader.vertexShader = shader.vertexShader.replace(
    "#include <common>",
      `
        #include <common>
        varying vec3 vPosition;
      `

  )
  shader.vertexShader = shader.vertexShader.replace(
    "#include <begin_vertex>",
      `
        #include <begin_vertex>
        vPosition = position;
      `
  )
  shader.fragmentShader = shader.fragmentShader.replace(
    "#include <common>",
      `
        #include <common>
        
        uniform vec3 uTopColor;
        uniform float uHeight;
        varying vec3 vPosition;
      `
  )
  shader.fragmentShader = shader.fragmentShader.replace(
    "#end#",
      `
        vec4 distGradColor = gl_FragColor;
        // 设置渐变色比例
        float gradMix = (vPosition.y+uHeight/2.0)/uHeight;
        // 设置渐变效果 mix(a,b,r) = (1-r)*a + br
        vec3 gradMixColor = mix(distGradColor.xyz,uTopColor,gradMix);
        // 片元赋色
        gl_FragColor = vec4(gradMixColor,0.8);
         //#end#
      `
  )
}